//
//  ConsolidatedPaymentController.m
//  NtoccShipper
//
//  Created by 张天兴 on 2024/5/11.
//  Copyright © 2024 zhuchongjin. All rights reserved.
//

#import "ConsolidatedPaymentController.h"
#import "ConsolidatePaymentCell.h"
#import "SourcesOrderListModel.h"
#import "ConsolidatedPaymentPayController.h"

@interface ConsolidatedPaymentController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (nonatomic,strong) NSString *strStatus;
@property (nonatomic, strong) CJButton * consolidatedButton;
@property (nonatomic, strong) NSString *strTitle;

@end

@implementation ConsolidatedPaymentController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitleName:CJLString(@"合并打款")];
    [self setBackLeftButton:@""];
    self.strTitle = @"";
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self.tableView registerNib:[UINib nibWithNibName:@"ConsolidatePaymentCell" bundle:nil] forCellReuseIdentifier:@"ConsolidatePaymentCell"];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.consolidatedButton];
    [self initData];
    [self downRefresh];
    
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
}

/// <#Description#>
- (void)loadData {
//    @[@"全部",@"未接单",@"已接单",@"已装货",@"已卸货",@"已核算",@"已完成""]
    self.strStatus = @"4";
    
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail",CJBaseUrl);
        NSDictionary *dicPar = @{
            @"pageNum":CJStringWithFormat(@"%d",self.page),
             @"pageSize":@"8",
             @"status":self.strStatus,
             @"mainOrderCode":self.strCode,
            @"isSettle":@"1",
            @"payStep":@"1",
            @"notEqualApplyStatus":@"1",
            @"shipType":@"shipPay",
        };

        WS(ws);
        [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {

            DLog(@"++++++++%@",responseObject);
            NSArray *list = responseObject[@"records"];
//            NSDictionary *dicSum = responseObject[@"sumObject"];
            NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
            
//            NSArray *listTitleNum = [[NSArray alloc]initWithObjects:
//                             CJStringWithFormat(@"%@",dicSum[@"allTrans"]),
//                             CJStringWithFormat(@"%@",dicSum[@"waitTrans"]),
//                             CJStringWithFormat(@"%@",dicSum[@"onTrans"]),
//                             CJStringWithFormat(@"%@",dicSum[@"waitSettle"]),
//                             CJStringWithFormat(@"%@",dicSum[@"waitPay"]),
//                             CJStringWithFormat(@"%@",dicSum[@"finishedTrans"]),
////                                 CJStringWithFormat(@"%@",dicSum[@""]),
//                             nil];
//            CJSendNotify(CJOrderDetailListBadgeNum, listTitleNum);
            
            if (list.count > 0) {

                if ([ws.refreshType isEqualToString:@"down"]) {
                    [ws.modelArray removeAllObjects];
                }

                NSError * error ;
                NSArray *arr = [SourcesOrderListModel arrayOfModelsFromDictionaries:list error:&error];
                [ws.modelArray addObjectsFromArray:arr];
      
                [ws.tableView.mj_header endRefreshing];
                [ws.tableView.mj_footer endRefreshing];

                if (ws.modelArray.count == total.intValue) {
                    [ws.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            
            }else{

                [ws.tableView.mj_header endRefreshing];
                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [ws.tableView reloadData];
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);
            [ws.tableView.mj_header endRefreshing];
            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
        }];

}

- (void)dealloc{
    CJRemoveNofify;
}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 145;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identifier = @"ConsolidatePaymentCell";
    ConsolidatePaymentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell ConsolidatePaymentCellfuzhi:self.modelArray[indexPath.row]];
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SourcesOrderListModel *model = self.modelArray[indexPath.row];
    if ([model.isSelected isEqualToString:@"1"]) {
        model.isSelected = @"0";
    }else{
        model.isSelected = @"1";
    }
    [self.tableView reloadRow:indexPath.row inSection:0 withRowAnimation:(UITableViewRowAnimationNone)];
    int numberStr = 0;
    for (SourcesOrderListModel *model1 in self.modelArray) {
        if ([model1.isSelected isEqualToString:@"1"]) {
            numberStr += 1;
        }
    }
    [self.consolidatedButton setTitle:CJStringWithFormat(@"合并打款（%d）个运单",numberStr) forState:(UIControlStateNormal)];
}
- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, CJTableToTopHeight + kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - kNavBarHeight -CJTableToTopHeight - 30),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}
- (CJButton *)consolidatedButton{
    if (!_consolidatedButton) {
        _consolidatedButton = CJButton.btnInit
        .btnFrame(CGRectMake(50,CGRectGetMaxY(self.tableView.frame) + 10,SCREEN_WIDTH - 100,50))
        .btnText(@"合并打款(0)个运单")
        .btnNormalTitleColor([UIColor cjWhiteColor])
        .btnBgColor([UIColor cjMainColor])
        .btnTargetAction(self, @selector(btnCancleAction:))
        .btnCornerRadius(10)
        .btnCornerWidth(1)
        .btnCornerColor([UIColor cjMainColor])
        ;
    }
    return _consolidatedButton;
}
- (void)btnCancleAction:(UIButton *)btn{
    NSString * orderDetailCodes = @"";
    int number = 0;
    for (SourcesOrderListModel *model in self.modelArray) {
        if ([model.isSelected isEqualToString:@"1"]) {
            orderDetailCodes = CJStringWithFormat(@"%@,%@",orderDetailCodes,model.code);
            number += 1;
        }
    }
    if (number == 0) {
        [CJAlert showStringDismissWithDelay:@"请先选择运单，再打款"];
        return;
    }else{
        orderDetailCodes = [orderDetailCodes substringFromIndex:1];
        ConsolidatedPaymentPayController *vc = [[ConsolidatedPaymentPayController alloc] init];
        vc.orderDetailCodes = orderDetailCodes;
        [self pushVc:vc];
    }
  
}
@end
